﻿(function ($, Ez) {
    Ez.loadJs(["hammer/hammer.min.js", "hammer/jquery.hammer.js"]);
    var _os = function () {
        var ua = navigator.userAgent,
        isWindowsPhone = /(?:Windows Phone)/.test(ua),
        isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
        isAndroid = /(?:Android)/.test(ua),
        isFireFox = /(?:Firefox)/.test(ua),
        isChrome = /(?:Chrome|CriOS)/.test(ua),
        isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
        isPhone = /(?:iPhone)/.test(ua) && !isTablet,
        isPc = !isPhone && !isAndroid && !isSymbian;
        return {
            isTablet: isTablet,
            isPhone: isPhone,
            isAndroid: isAndroid,
            isPc: isPc
        };
    }();
    var MoveEnable = function (opts, callback) {
        if (typeof (parent) == 'string') parent = $(parent);
        var that = this;
        that.config = $.extend({}, opts)
        if (that.config.wrapper) {
            that.config.wrapper.css({ "position": "relative" });
        }
        else {
            that.config.wrapper = $(document);
        }
        that.target = that.config.wrapper.find(".jstarget").css({ "position": "absolute" });

        var id = that.target.attr("id");
        if (!id) {
            that.target.attr("id", ("ezcutfast_img_" + Math.random()).replace(".", ""));
        }
        var moveinfo = {};
        var movestart = function (_e) {
            var e = _e.gesture && _e.gesture.srcEvent ? _e.gesture.pointers[0] : _e;
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                window.event.returnValue = false;
            }
            var $target = $(e.target);
            if ($target.attr("ezcutfast-img") == 'y') {
                $(document).on("mousedown", movestart);

                var id = $target.attr("id");
                moveinfo = {
                    status: 'moving',
                    target: $target,
                    spoint: { x: e.clientX, y: e.clientY },
                    epoint: { x: e.clientX, y: e.clientY },
                    distance: function () {
                        return { xlen: this.epoint.x - this.spoint.x, ylen: this.epoint.y - this.spoint.y }
                    },
                    update: function (x, y) {
                        this.spoint = { x: this.epoint.x, y: this.epoint.y };
                        this.epoint = { x: x, y: y };
                    }
                }
            }
        }
        var moving = function (_e) {

            if (moveinfo.status == "moving") {

                var e = _e.gesture && _e.gesture.srcEvent ? _e.gesture.pointers[0] : _e;
                //for (var key in e) {
                //    $("#output").append(key + "=" + e[key]+"<br/>");
                //}

                moveinfo.update(e.clientX, e.clientY);
                var distance = moveinfo.distance();
                if (distance.xlen != 0) {
                    var curpos = moveinfo.target.position();

                    var newpos = {};
                    var offset = that.config.wrapper.offset();
                    if (e.clientX >= offset.left && (offset.left + moveinfo.target.width()) >= e.clientX) {
                        newpos.left = curpos.left + distance.xlen;
                    }
                    if (e.clientY >= offset.top && (offset.top + moveinfo.target.height()) >= e.clientY) {
                        newpos.top = curpos.top + distance.ylen;
                    }
                    moveinfo.target.css(newpos);
                    callback && callback(newpos);
                }
            }
        }
        var movefinish = function (e) {
            moveinfo.status = "finish";
            moveinfo = {};
            $(document).off("mousedown");

        }
        that.target.css({ "position": "absolute" });
        that.target.attr("ezcutfast-img", 'y');
        if (!_os.isPc) {
            ; (function (that) {
                //document.addEventListener('touchmove', function (event) { event.preventDefault(); }, false);
                //try { navigator.control.gesture(false); } catch (e) { } //UC浏览器关闭默认手势事件
                //try { navigator.control.longpressMenu(false); } catch (e) { } //关闭长按弹出菜单

                that.target.hammer({});
                $(document).hammer({});
                that.target.on("pinchin pinchout panstart press", function (e) {
                    if (e.type != "pinchin" && e.type != "pinchout") movestart(e);

                })
                $(document).on("pinchin pinchout panmove panend pressup pancancel", function (e) {

                    if (e.type == "panmove") {
                        moving(e)
                    }
                    else if (e.type != "pinchin" && e.type != "pinchout") {
                        movefinish(e);
                    }
                })
            })(that)
        }
        else {
            ; (function (that) {
                that.target.on("mousedown", movestart);
                $(document).on("mousemove", moving).on("mouseup", movefinish);
                var id = that.target.attr("id");
                if (!id) {
                    that.target.attr("id", ("ezcutfast_img_" + Math.random()).replace(".", ""));
                }
            })(that)
        }
    }

    MoveEnable.prototype = {
        destory: function () {
            if (!_os.isPc) {
                this.target.off("pinchin pinchout panstart press");
                $(document).off("pinchin pinchout panmove panend pressup pancancel mousedown")
            }
            else {
                this.target.off("mousedown")
                $(document).off("mousemove mouseup");
            }
        }
    }
    var Cutitem = function (wrapper, opts) {
        this.target = wrapper.find(".jstarget");
        if (this.target.length == 0)
        {
            console.error("请给要处理的图片设置脚本样式 .jstarget");
            return;
        }
        this.wrapper = wrapper;
        var that = this;
        that.config = $.extend({ cutHeight:this.wrapper.height()|| 200, cutWidth:this.wrapper.width() || 200 }, opts);

        var img = new Image();
        img.onload = function () {
            img.onload = null;
            that.config.sourceHeight = img.height;
            that.config.sourceWidth = img.width;
        }
        img.src = that.target.attr("src");

        that.moveobj = new MoveEnable({ wrapper: wrapper }, function (pos) {
            var data = that.postData();
            that.config.callback && that.config.callback(that.postData());
        });
        var zoom = 100;



        if (_os.isPc) {
            that.target.on("mousewheel DOMMouseScroll", function (e) {
                var $this = $(this);
                var delta = e.originalEvent.wheelDelta ||  // chrome & ie
                           e.originalEvent.detail * -40; // firefox
                zoom += delta / 12;
                if (zoom > 20 && zoom < 200) {
                    var mx = e.clientX || e.originalEvent.clientX,
                        my = e.clientY || e.originalEvent.clientY,
                        offset = $this.offset(),
                        wrapper_offset = that.wrapper.offset();
                    dif_x = mx - offset.left,
                    dif_y = my - offset.top,
                    rate_x = dif_x / $this.width(),
                    rate_y = dif_y / $this.height(),
                    pos = $this.position(),
                    new_width = that.config.sourceWidth * (zoom * 1.0 / 100),
                    new_height = $this.width(new_width).data("zoom", zoom).height(),
                    new_dif_x = new_width * rate_x, new_dif_y = new_height * rate_y,
                    newleft = mx - new_dif_x - wrapper_offset.left,
                    newtop = my - new_dif_y - wrapper_offset.top;
                    $this.css({ top: newtop, left: newleft });
                    that.config.callback && that.config.callback(that.postData());
                }
                else if (zoom <= 20) {
                    zoom = 20;
                }
                else if (zoom >= 200)
                {
                    zoom = 200;
                }
            })
        }
        else {
            that.target.data("hammer").get('pinch').set({ enable: true });
            $(document).data("hammer").get('pinch').set({ enable: true });
            $(document).on("pinch", function (e) {
                if (e.gesture.pointers.length == 2) {
                    that.target.data("pinch-active", true);
                    that.target.data("predistance", e.gesture.distance);
                }
            }).on("pinchend pinchcancel", function () {
                that.target.data("pinch-active", false);
            })
            zoom = 100;
            var activetype = "";
            $(document).on("pinchin pinchout", function (e) {
                if (that.target.data("pinch-active")) {
                    if (e.gesture.pointers.length == 2) {
                        var new_width;
                        activetype = activetype!=e.type?e.type:activetype;

                        if (e.type == "pinchin" && activetype == e.type) {
                            activetype = e.type;
                            zoom = zoom - 0.2;
                            new_width = that.config.sourceWidth * (zoom * 1.0 / 100);
                            $("#output").append(new_width + "<br>");
                        }
                        else if (activetype == e.type) {
                            activetype = e.type;
                            zoom = zoom + 0.2;
                            new_width = that.config.sourceWidth * (zoom * 1.0 / 100);
                        }
                        new_height = that.target.width(new_width).data("zoom", zoom).height();
                        that.config.callback && that.config.callback(that.postData());
                    }
                }

            })
        }
    }
    Cutitem.prototype = {
        postData: function () {
            var targetpos = this.target.position(),
                cut_sx = targetpos.left,
                cut_sy = targetpos.top,
                cut_ex = cut_sx + this.config.cutWidth,
                cut_ey = cut_sx + this.config.cutHeight,
                zoom = this.target.data("zoom"),
                imageurl = this.target.attr("src");
            return { cut_sx: cut_sx, cut_sy: cut_sy, cut_ex: cut_ex, cut_ey: cut_ey, zoom: zoom || 100, cutHeight: this.config.cutHeight, cutWidth: this.config.cutWidth, imageurl: imageurl };
        },
        destory: function () {
            this.target.css({ width: "auto", height: "auto", top: 0, left: 0 });
            if (_os.isPc) {
                this.target.off("mousewheel DOMMouseScroll");
            }
            else {
                $(document).off("pinch pinchend pinchcancel");
                this.target.off("pinchin pinchout");
            }
            this.moveobj.destory();
        }
    }
    $.fn.avatarcut = function (opts) {
        return this.each(function () {
            var that = $(this);
            var api = new Cutitem(that, opts);
            that.data("api", api);
        })
    }
})(jQuery, Ez)